package com.jservice.web.sysOffice;


import com.jfinal.aop.Before;
import com.jservice.framework.annotation.RouteBind;
import com.jservice.framework.dto.Message;
import com.jservice.model.SysOffice;
import com.jservice.web.base.JBaseController;

import java.util.List;

/**
 * OfficeController
 *
 * @author cwvian
 * @version 1.0
 * @date 2017/5/11
 */
@RouteBind(path = "/admin/office")
public class OfficeController extends JBaseController{

	public void list(){
		List<SysOffice> officeTree = SysOfficeService.me().findTree();
		setAttr("officeTree", officeTree);
		render("list");
	}

	public void add() {
		String parentId = getPara("id");

		List<SysOffice> officeTree = SysOfficeService.me().findTree();
		setAttr("officeTree", officeTree);
		setAttr("parentId", parentId);

		render("add");
	}

	public void edit() {
		String id = getPara("id");

		SysOffice office =  SysOfficeService.DAO.findById(id);
		setAttr("office", office);

		List<SysOffice> officeTree =  SysOfficeService.me().findTree();
		setAttr("officeTree", officeTree);

		setAttr("children", SysOfficeService.me().findChildren(office));

		render("edit");
	}

	@Before(OfficeValidator.class)
	public void save() {
		SysOffice office = getModel(SysOffice.class,"office");
		if( SysOfficeService.me().save(office)){
			setFlashMessage(Message.success("保存成功！"));
		}else{
			setFlashMessage(Message.error("保存失败！"));
		}
		redirect("/admin/office/list");
	}

	@Before(OfficeValidator.class)
	public void update() {
		SysOffice office = getModel(SysOffice.class,"office");
		if( SysOfficeService.me().update(office)){
			setFlashMessage(Message.success("修改成功！"));
		}else{
			setFlashMessage(Message.error("修改失败！"));
		}
		redirect("/admin/office/list");
	}

	public void delete() {
		String id = getPara("id");

		SysOffice office = SysOfficeService.DAO.findById(id);

		if( SysOfficeService.me().findChildren(office).size() > 0){
			renderJson(Message.warn("存在下级部门，不允许删除！"));
			return;
		}

		if( SysOfficeService.me().delete(id)){
			renderJson(Message.success("删除成功！"));
		}else{
			renderJson(Message.error("删除失败！"));
		}
	}

}
